package com.dataart.training.crimequalification.beans;

import com.dataart.training.crimequalification.entity.QualificationTaskEntity;
import com.dataart.training.crimequalification.service.QualificationTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@ManagedBean
@Controller
@Scope("request")
public class ChooseTaskBean {

    //-----------------------------------------------------------------

    private List<QualificationTaskEntity> tasks;

    //-----------------------------------------------------------------

    @Autowired
    private QualificationTaskService qualificationTaskService;

    //-----------------------------------------------------------------

    @PostConstruct
    private void init() {
        tasks = qualificationTaskService.getAllTasks();
    }

    public void taskAlreadyChosenRedirect() throws IOException {

        ConfigurationUtils confUtils = new ConfigurationUtils();

        if (confUtils.isTaskChosen(FacesContext.getCurrentInstance())) {

            HttpServletRequest request =
                    (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            FacesContext.getCurrentInstance().getExternalContext().redirect(request.getContextPath()
                    + "/views/crimequalificator.xhtml");

        }

    }

    /**
     * @param task
     * @return
     */
    public String trimTaskText(QualificationTaskEntity task) {
        return StringUtils.substring(task.getTaskText(), 0, 40) + "...";
    }

    /**
     * @param task
     * @return
     */
    public String composeURLToTask(QualificationTaskEntity task) {
        return "/views/crimequalificator?faces-redirect=true&taskId=" + task.getTaskId().toString();
    }

    //-----------------------------------------------------------------

    public List<QualificationTaskEntity> getTasks() {
        return tasks;
    }

    public void setTasks(List<QualificationTaskEntity> tasks) {
        this.tasks = tasks;
    }
}
